﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GameServer
{
    /// <summary>
    /// 游戏线程
    /// </summary>
    public class GameThread : GameThreadBase
    {
        /// <summary>
        /// 当前线程中游戏线程对象列表
        /// </summary>
        private List<IThreadSafeGameThread> threadList = new List<IThreadSafeGameThread>();

        /// <summary>
        /// 游戏线程同步锁对象
        /// </summary>
        private static Object gameThreadLock = new Object();

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="tag">线程名</param>
        public GameThread(String tag)
            : base(tag)
        {
        }

        /// <summary>
        /// 添加一个线程对象到游戏线程中
        /// </summary>
        /// <param name="gameThread">游戏线程对象</param>
        public void Add(IThreadSafeGameThread gameThread)
        {
            lock (gameThreadLock)
            {
                if (threadList.Contains(gameThread))
                {
                    // todo:添加失败时进行的操作
                }
                else
                {
                    threadList.Add(gameThread);
                }
            }
        }

        /// <summary>
        /// 重载基类的Run函数,驱动游戏线程对象
        /// </summary>
        public override void Run()
        {
            while (true)
            {
                base.Run();

                // 读取线程中的线程对象到临时变量中
                List<IThreadSafeGameThread> _gameThreadList = new List<IThreadSafeGameThread>();
                lock (gameThreadLock)
                {
                    _gameThreadList = threadList;
                }

                // 驱动线程对象中的Run函数和GameSecLoop函数
                foreach (IThreadSafeGameThread gameThread in _gameThreadList)
                {
                    if (gameThread != null)
                    {
                        gameThread.Run();
                        if (Global.DateTime.Second != DateTime.Now.Second)
                        {
                            Global.DateTime = DateTime.Now;
                            gameThread.GameSecLoop();
                        }
                    }
                }
            }
        }
    }
}
